package cmbchina.util;


import com.fasterxml.jackson.databind.JsonNode;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

/**
 *
 * 调用itil工具类
 */
public class ScriptRequestUtil {

    private static final Logger logger = LoggerFactory.getLogger(FlowScriptRunUtils.class);
    public static Properties appConfig = AppConfig.getInstance().getConfig();
    private static  String dashboard_url= appConfig.getProperty("dashboard.url");
    private static String dashboard_usernmae = appConfig.getProperty("dashboard.username") ;
    private static String dashboard_passWorld = appConfig.getProperty("dashboard.password");
    private static int dashboard_port =Integer.parseInt(appConfig.getProperty("dashboard.port"));
    private static String dashboard_protocol = "http";
    private static String dashboard_apiurl =appConfig.getProperty("dashboard.apiurl");
/*
    private static  String dashboard_url= "99.1.76.195";
    private static String dashboard_usernmae =  "sjkjkpt";
    private static String dashboard_passWorld = "sjkjkpt@123456";
    private static int dashboard_port = 80;
    private static String dashboard_protocol = "http";
    private static String dashboard_apiurl = "/ngap/api/operation/rs6000/exec_command";*/

    /**
     * rest post 方式调用itil接口
     * @param JsonParams json格式的请求参数
     * @return
     * @throws Exception
     */
    public static Map<String,Object> httpRequestPost(String JsonParams)throws Exception{

        HttpHost targetHost = new HttpHost(dashboard_url, dashboard_port, dashboard_protocol);

        DefaultHttpClient httpclient = new DefaultHttpClient();
       /* 请求超时*/
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000*60*60);
        /*读取超时*/
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000*60*60);

        //此用户名和密码上生产前需要修改为自己的账户
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(dashboard_usernmae, dashboard_passWorld));

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        String url = dashboard_protocol+"://"+dashboard_url+":"+dashboard_port+dashboard_apiurl;

        logger.error("run script request url info ====" + url);
        logger.error("username + password ====" + dashboard_usernmae +"--" + dashboard_passWorld);
        logger.error("run script request json ====" + JsonParams);

        HttpPost httpPost = new  HttpPost(url);

        StringEntity stringEntity = new StringEntity(JsonParams, HTTP.UTF_8);

        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("accept","application/json");

        httpPost.setEntity(stringEntity);

        HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);

        HttpEntity entity = response.getEntity();

        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("StatusCode:" + statusCode);
        Map<String,Object> mapResult = new HashMap<String,Object>();

        if(statusCode == 200) {

            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),"utf-8"));
            String buffer  = "";
            StringBuffer sb = new StringBuffer();
            while((buffer = reader.readLine())!=null){
                sb.append(buffer);
                sb.append("<br>");
            }
            reader.close();
            httpPost.releaseConnection();
            System.out.println("entity:" + sb.toString());
            httpclient.getConnectionManager().shutdown();

            JsonNode jsonNode = JacksonUitl.getObjectMapper().readTree(sb.toString());
            JsonNode result  = jsonNode.get(0);

            List<String> list = JacksonUitl.getObjectMapper().readValue(result.get("output").toString(),List.class);


            mapResult.put("returnCode",result.get("returnCode").toString());
            mapResult.put("outPut",list);
            mapResult.put("hostName",result.get("host_name").toString());

        }else{

            mapResult.put("returnCode",statusCode);
            mapResult.put("outPut",null);
            mapResult.put("hostName","");

        }



        return mapResult;

    }



    public static void main(String[] args) throws Exception {

        String pp = "{\"shellName\":\"ls \", \"shellParam\":\"\", \"hostNames\":\"\", \"userName\":\"\"}";
        Map<String,Object> mapResult = ScriptRequestUtil.httpRequestPost(pp);
        System.out.println("Hello World");

    }

}
